from flask import Flask, request, jsonify
from similarity import similarities
from similarity.caculatetfidf import caculatetfidf, calculate_tdidf_from_db
from word2vec.word2vec import get_similarity_word_2_vec
import db.db_init as db
import logging

app = db.create_app()

# 设置日志记录
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)


@app.route('/calc', methods=['POST', 'GET'])
def calc():
    logger.debug(f"Handling calc request: {request}")
    if request.method == 'POST':
        text = request.form.get('text')
        createTime = request.form.get('createTime')
    else:
        text = request.args.get('text')
        createTime = request.args.get('createTime')
    if text is None:
        return "请输入参数"
    result_similarities_top10, result_str = similarities.getSimilarity_top10_from_db(text, createTime)
    return jsonify(result_str)


@app.route('/calc_extended', methods=['POST', 'GET'])
def calc_extended():
    logger.debug(f"Handling calc request: {request}")
    if request.method == 'POST':
        text = request.form.get('text')
        createTime = request.form.get('createTime')
    else:
        text = request.args.get('text')
        createTime = request.args.get('createTime')
    if text is None:
        return "请输入参数"
    result_str = similarities.getSimilarity_top10_from_db_extended(text, createTime)
    return jsonify(result_str)


@app.route('/')
def index():
    logger.debug(f"Handling index request: {request}")
    return 'Hello World!'


@app.route('/get_corpus_from_db')
def get_corpus_from_db():
    logger.debug(f"Handling get_corpus_from_db request: {request}")
    return calculate_tdidf_from_db()


@app.route('/calc_vec')
def calc_vec():
    logger.debug(f"Handling calc_vec request: {request}")
    text = request.args.get('text')
    if text is None:
        return "请输入参数"
    result_similarities_top10, result_str = get_similarity_word_2_vec(text)
    return result_str


if __name__ == '__main__':
    app.run()
